"""
This module defines the template tags for the mediamanager. For more
information about the usage read the documentation.

:Author: Sven Walter <sven.walter@wltr.eu>
:Since: 02/08/2011
"""

from django import template

from ..utils.manager import MediaManager


register = template.Library()


class ManageNode(template.Node):
    """ Node for all manage tags. """
    
    def __init__(self, resource, size=None, crop=None):
        self.resource = resource
        self.size = size 
        self.crop = crop
    
    def render(self, context): #@UnusedVariable
        if isinstance(self.resource, template.Variable):
            resource = unicode(self.resource.resolve(context))
        else:
            resource = self.resource
            
        manager = MediaManager.cached(resource, size=self.size, crop=self.crop)
        return manager.get_url()
    

@register.tag
def mediamanager(parser, token):
    """ This function validates the token and extracts the resource and expire
    variables. It is used by all three manage_* tags.
    
    Usage: {% <tag_name> "<resource_file>" [<size>|<width>x<height>] [expire=<expire>] %} """
    
    bits = token.split_contents()
    
    # tag_name
    tag_name = bits.pop(0)
    
    error = ('Wrong usage for %r tag: {%% %r "<resource_file>" '
             '[<size>|<width>x<height>] [crop=<x,y,w,h>] %%}.') % (tag_name, tag_name)
    

    # resource
    bit = bits.pop(0)
    if not (bit[0] == bit[-1] and bit[0] in ('"', "'")):
        resource = template.Variable(bit)
    else:
        resource = bit[1:-1]
        
    size = None
    crop = None
    
    # size
    if len(bits) > 0:
        bit = bits.pop(0)
        
        try:
            w, h = bit.split('x', 1)
            size = int(w), int(h)
        except ValueError:
            try:
                size = int(bit), int(bit)
            except ValueError:
                raise (template.TemplateSyntaxError, error + '(2)')
            
    if len(bits) > 0:
        bit = bits.pop(0)
        
        if bit.startswith("crop="):
            crop = bit[5:].split(',',3)
            crop = [ int(c) for c in crop]
            
    return ManageNode(resource, size=size, crop=crop)
